/*
 * HoldLotAction.java
 *
 * Created on June 9, 2002, 1:23 AM
 */

package com.scalar.chiptrack.operations.process.actions;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.chiptrack.engineering.dao.EngineeringDAO;
import com.scalar.chiptrack.operations.LotView;
import com.scalar.chiptrack.operations.process.FinishedGoods;
import com.scalar.chiptrack.operations.process.dao.FinishedGoodsDAO;
import com.scalar.chiptrack.operations.process.dao.PartNumber;
import com.scalar.chiptrack.operations.process.dao.ProductDao;
import com.scalar.chiptrack.operations.process.forms.SplitMergeForm;
import com.scalar.chiptrack.users.User;

/**
 *
 * @author  Mallikarjun
 * @version 1.0
 */
public class SplitMergeAction extends ChipTrackAction
{
       private static final String ACTION_NAME = "/splitMergeLot.do";
       public ActionForward execute (ActionMapping mapping,
                                      ActionForm form,
                                      HttpServletRequest request,
                                      HttpServletResponse response)
                                      throws Exception
       {
            SplitMergeForm splitMergeForm = (SplitMergeForm)form;

            HttpSession session = request.getSession ();
            User user = (User)session.getAttribute(SessionKeys.USER_KEY);
            if ( user == null )
            {
                session.setAttribute ( SessionKeys.SOURCE_PAGE_KEY, ACTION_NAME + "?" + request.getQueryString () );
                return ( mapping.findForward ( "login" ) );
            }
            DBTransaction dbt = null;

            boolean success = false;
            HashMap errors = new HashMap();
            
            String lotaction = request.getParameter("lotaction");
            String selectedPartNumber = splitMergeForm.getPartNumber();
            String lotNumber = splitMergeForm.getLotNumber();
            String processStep = "";
            String from = null;
            ArrayList marketingProducts = null;
            ArrayList partNumberList = null;
            // Added by veeru on 14th July 2004
            if ( lotNumber != null && !"null".equalsIgnoreCase(lotNumber))
            {
                lotNumber = lotNumber.trim();
            }
            if( "Select Product".equalsIgnoreCase(selectedPartNumber) && ( (lotaction == null) || "".equalsIgnoreCase(lotaction)) )
            {
                selectedPartNumber = "0";
                lotaction = "LOT_SEARCH";
            }
            if((lotaction == null) || "".equalsIgnoreCase(lotaction))
            {
                 partNumberList = FinishedGoodsDAO.loadAllFinishedGoodsWithoutBoardAndKits();
                 marketingProducts =new ArrayList();
                 FinishedGoods finishedGoods = null;
                 for(int i=0;i<partNumberList.size();i++)
                 {
                    finishedGoods = (FinishedGoods)partNumberList.get(i);
                    marketingProducts.add( new org.apache.struts.util.LabelValueBean
                    ( finishedGoods.getManufacturingPartNo() ,
                    String.valueOf( finishedGoods.getProcessStepId() ) ) );
                 }

			    from = "LOT_SEARCH";
                session.setAttribute("marketingProducts", marketingProducts);
                // Modified by veeru on 19th July 2004
                request.setAttribute("processSteps", EngineeringDAO.getProcessSteps());

                request.setAttribute("showList", "FALSE");
                request.setAttribute("from", from);
                request.setAttribute ( SessionKeys.ERROR_MESSAGES, errors );
                request.setAttribute ("splitMergeLot",splitMergeForm);
                return mapping.findForward("show");
            }
            // End of Added by veeru
            if((lotaction != null) && lotaction.equalsIgnoreCase("LOAD_PRODUCTS"))
            {
                processStep = request.getParameter("process");
            	if("Finished Goods".equalsIgnoreCase (processStep) || processStep == null || "".equals(processStep) )
                {
					 partNumberList = FinishedGoodsDAO.loadAllFinishedGoodsWithoutBoardAndKits();
					 marketingProducts =new ArrayList();
					 FinishedGoods finishedGoods = null;
					 for(int i=0;i<partNumberList.size();i++)
                     {
						finishedGoods = (FinishedGoods)partNumberList.get(i);
						marketingProducts.add( new org.apache.struts.util.LabelValueBean 
						( finishedGoods.getManufacturingPartNo() , 
						String.valueOf( finishedGoods.getProcessStepId() ) ) );
				    }
			    }
			    if ( ( "FAB".equalsIgnoreCase (processStep) ) ||  ( "SORT".equalsIgnoreCase (processStep) )
				    || ( "Assembly".equalsIgnoreCase (processStep) ) || ( "TEST".equalsIgnoreCase (processStep) )
				    || ( "Die Bank".equalsIgnoreCase (processStep) ) || ( "Wafer Store".equalsIgnoreCase (processStep) )
                    || "Mark & Pack".equalsIgnoreCase (processStep) || "Class Store".equalsIgnoreCase (processStep) )
                {

			    	PartNumber partNumber = null;
                    partNumberList = ProductDao.getPartNumber(processStep);
                    marketingProducts =new ArrayList();
                    for(int i=0;i<partNumberList.size();i++)
                    {
                        partNumber=(PartNumber)partNumberList.get(i);
                        marketingProducts.add ( new org.apache.struts.util.LabelValueBean
                            ( partNumber.getPartNumber (), partNumber.getProcessStepId ()  ) );
                    }
                }
                from = "LOT_SEARCH";
                // Added by veeru 25th June 2004
                if( marketingProducts == null )
                {
                    marketingProducts =new ArrayList();
                    errors.put("Error ","No Products found for this Process Step");
                }
                request.setAttribute("marketingProducts", marketingProducts);
                // End of Added by veeru
                request.setAttribute("processSteps", EngineeringDAO.getProcessSteps());
                request.setAttribute("showList", "FALSE");
                request.setAttribute("from", from);
                request.setAttribute ( SessionKeys.ERROR_MESSAGES, errors );
                request.setAttribute ("splitMergeLot",splitMergeForm);

                return mapping.findForward("show");
            }

            if((lotaction != null) && lotaction.equalsIgnoreCase("LOT_SEARCH"))
            {
                from = "LOT_SEARCH";
                processStep = splitMergeForm.getProcessStep();

                ArrayList activeLots = EngineeringDAO.getActiveLots(selectedPartNumber, lotNumber, processStep);

				if("Finished Goods".equalsIgnoreCase (processStep) || (processStep == null) || ("".equalsIgnoreCase(processStep)))
                {
					 partNumberList = FinishedGoodsDAO.loadAllFinishedGoodsWithoutBoardAndKits();
					 marketingProducts =new ArrayList();
					 FinishedGoods finishedGoods = null;
					 for(int i=0;i<partNumberList.size();i++)
                     {
						finishedGoods = (FinishedGoods)partNumberList.get(i);
						marketingProducts.add( new org.apache.struts.util.LabelValueBean 
						( finishedGoods.getManufacturingPartNo() , 
						String.valueOf( finishedGoods.getProcessStepId() ) ) );
					 }
				}
				
            	if (       "FAB".equalsIgnoreCase (processStep)  ||   "SORT".equalsIgnoreCase (processStep)
					    || "ASSEMBLY".equalsIgnoreCase (processStep)  ||  "TEST".equalsIgnoreCase (processStep)
					    || "DIE BANK".equalsIgnoreCase (processStep)  ||  "WAFER STORE".equalsIgnoreCase (processStep)
                            // Added by veeru 16th July 2004
                        || "Class Store".equalsIgnoreCase (processStep) || "Mark & Pack".equalsIgnoreCase (processStep)  )
                {

                    PartNumber partNumber = null;
                    partNumberList = ProductDao.getPartNumber(processStep);
                    marketingProducts =new ArrayList();
                    for(int i=0;i<partNumberList.size();i++)
                    {
                        partNumber=(PartNumber)partNumberList.get(i);
                        marketingProducts.add ( new org.apache.struts.util.LabelValueBean
                            ( partNumber.getPartNumber (), partNumber.getProcessStepId ()  ) );
                    }
				}
				
                request.setAttribute("activeLots", activeLots);
                // Added by veeru 25th June 2004
                if( marketingProducts == null )
                {
                    marketingProducts =new ArrayList();
                    errors.put("Error ","No Products found for this Process Step");
                }
                request.setAttribute("marketingProducts", marketingProducts);

                if( activeLots.size() > 0 )
                {
                    request.setAttribute("showList", "TRUE");
                }
                else
                {
                    errors.put("Error ","No Lots found with the given search criteria");
                }
                // End of Added by veeru
                request.setAttribute("processSteps", EngineeringDAO.getProcessSteps());
                request.setAttribute("from", from);
                request.setAttribute ( SessionKeys.ERROR_MESSAGES, errors );
                request.setAttribute ("splitMergeLot",splitMergeForm);

                return mapping.findForward("show");

            }

            if((lotaction != null) && lotaction.equalsIgnoreCase("LOT_SPLIT"))
            {

                from = "LOT_SPLIT_SAVE";
                String status = request.getParameter("status");
                String temp_lot_number = request.getParameter("tempLotNumber");
                String temp_lot_id = request.getParameter("lotid");
                
                if(status.equalsIgnoreCase("ACTIVE"))
                {
                	status = "Running";
                }

                LotView lview = EngineeringDAO.getCurrentLotPosition(temp_lot_number, status, temp_lot_id);
                ArrayList splitList = EngineeringDAO.getSplitLots(temp_lot_number);

                request.setAttribute("lview", lview);
                request.setAttribute("splitList", splitList);
                request.setAttribute("from", from);
                request.setAttribute("showList", "TRUE");

                return mapping.findForward("split");

            }

            if((lotaction != null) && lotaction.equalsIgnoreCase("LOT_MERGE"))
            {

                from = "LOT_MERGE_SAVE";
                String status = request.getParameter("status");
                String temp_lot_number = request.getParameter("tempLotNumber");
                String temp_lot_id = request.getParameter("lotid");


                if(status.equalsIgnoreCase("ACTIVE"))
                {
                	status = "Running";
                }
                LotView lview = EngineeringDAO.getCurrentLotPosition(temp_lot_number, status, temp_lot_id);
                // Added by veeru on 29th June 2004
                ArrayList activeLots = EngineeringDAO.getActiveLots("0","","");
                LinkedHashMap activeLotsMap = new LinkedHashMap();
                LotView lotView             = new LotView();
                for( int i = 0 ; i < activeLots.size(); i++ )
                {
                    lotView = (LotView)activeLots.get(i);
                    if ( lotView.getCurrentProcess().equalsIgnoreCase( lview.getCurrentProcess() ) &&
                         lotView.getStatus().equalsIgnoreCase("ACTIVE") &&
                         lotView.getProcessStepID().equalsIgnoreCase( lview.getProcessStepID() ) &&
                         lotView.getLocationID().equalsIgnoreCase( lview.getLocationID() ) &&
                         !temp_lot_number.equalsIgnoreCase( lotView.getLotNumber() ) )
                    {

                        if( ("ACTIVE").equalsIgnoreCase( lotView.getStatus() ) )
                        {
                            lotView.setStatus("Running");
                        }
                        LotView tempLotview = EngineeringDAO.getCurrentLotPosition(lotView.getLotNumber(), lotView.getStatus(), lotView.getLotID() );
                        if( tempLotview != null )
                        {
                            lotView.setQuantityIn( tempLotview.getQuantityIn() );
                        }
                        activeLotsMap.put(lotView.getLotNumber(),lotView);
                    }
                }
                session.setAttribute("activeLotsMap", activeLotsMap);
                // End of Added by veeru

                request.setAttribute("lview", lview);
                request.setAttribute("from", from);
                request.setAttribute("showList", "TRUE");

                return mapping.findForward("merge");
            }

            if((lotaction != null) && lotaction.equalsIgnoreCase("LOT_CONFIRM"))
            {
                //from = "LOT_HOLD";
                String temp_lot_number = request.getParameter("tempLotNumber");
                String status = request.getParameter("status");
                String temp_from = request.getParameter("flag");
                //System.out.println("Flag = "+ temp_from);
                //System.out.println("tempLotNumber = "+ temp_lot_number);
                LotView lview = EngineeringDAO.getCurrentLotPosition(temp_lot_number, status);

                request.setAttribute("lview", lview);

                if((temp_from != null) && (!temp_from.equalsIgnoreCase("")))
                {

                        if(temp_from.equalsIgnoreCase("Hold"))
                        {
                		    request.setAttribute("from", "LOT_HOLD");
                        }
                        else
                        {
                              request.setAttribute("from", "LOT_RELEASE");
                        }
                }

                return mapping.findForward("hold");
            }

            if((lotaction != null) && lotaction.equalsIgnoreCase("LOT_HOLD") )
            {
                //HttpSession hs = request.getSession(false);
                LotView lview = (LotView)session.getAttribute(SessionKeys.LOT_VIEW);
                String comments = request.getParameter("comments");
                //User user = (User)hs.getAttribute(SessionKeys.USER_KEY);
                //System.out.println("LotView = "+lview);
                //System.out.println("comments = "+ comments);

	            /*try{
	        	dbt = DBTransaction.getInstance();
	                dbt.begin();
	                int holdId = 0;
	                int alarmId = 0;

	                //operation 1
	                holdId = EngineeringDAO.holdLot(dbt, lview, comments, "Hold");

                        //operation 2
	                alarmId = EngineeringDAO.sendAlarm(dbt,
							     "LOT_HOLD",
							     user,
							     lview,
	                				     comments,
	                				     0);


                        System.out.println("Hold ID = "+ holdId);
                        System.out.println("Alarm ID = "+ alarmId);

	                //operation 3
	                EngineeringDAO.updateAlarmID(dbt, "LOT_HOLD", holdId, alarmId);

	                success = true;

		}catch(Exception e){

	               e.printStackTrace();
	               throw new ScalarException("HoldLotAction failed", e);

	        }finally{

	        	if(success){
	                   dbt.commit();
	                   errors.put("Scrap ", "Hold Action Successfull");
	                   errors.put("E-mail ", "Mail has been sent");
			}else{
	                    dbt.rollback();
	                }

	                hs.removeAttribute(SessionKeys.LOT_VIEW);
		}

	        if(!errors.isEmpty()) {
                    request.setAttribute(SessionKeys.MESSAGES, errors);
                }

                return mapping.findForward("engConfirm");
               */
            }

            if((lotaction != null) && lotaction.equalsIgnoreCase("LOT_RELEASE") ){

                //HttpSession hs = request.getSession(false);
                LotView lview = (LotView)session.getAttribute(SessionKeys.LOT_VIEW);
                String comments = request.getParameter("comments");
                //User user = (User)hs.getAttribute(SessionKeys.USER_KEY);
                //System.out.println("This is release comments = "+ comments);

	       /*try{
	        	dbt = DBTransaction.getInstance();
	                dbt.begin();
	                int holdId = 0;
	                int alarmId = 0;

	                //operation 1
	                holdId = EngineeringDAO.holdLot(dbt, lview, comments, "Rlease");

                        //operation 2
	                alarmId = EngineeringDAO.sendAlarm(dbt,
							     "LOT_RELEASE",
							     user,
							     lview,
	                				     comments,
	                				     0);


                        System.out.println("Release ID = "+ holdId);
                        System.out.println("Alarm ID = "+ alarmId);

	                //operation 3
	                EngineeringDAO.updateAlarmID(dbt, "LOT_RELEASE", holdId, alarmId);

	                success = true;

		}catch(Exception e){

	               e.printStackTrace();
	               throw new ScalarException("HoldLotAction failed", e);

	        }finally{

	        	if(success){

	                   dbt.commit();
	                   errors.put("Scrap ", "Lot Release Action Successfull");
	                   errors.put("E-mail ", "Mail has been sent");

			}else{
	                    dbt.rollback();
	                }

	                hs.removeAttribute(SessionKeys.LOT_VIEW);
		}

	        if(!errors.isEmpty()) {
                    request.setAttribute(SessionKeys.MESSAGES, errors);
                }

                return mapping.findForward("engConfirm");
               */
            }

            return null;
       }
}
